<template>
  <div class="alert">
    <div
      class="alert-main"
      v-for="item in notices"
      :key="item.name"
    >
      <div class="alert-content">
        <div class="conten">
          <i class="alert-icon" :class="'alert-icon-' + item.type"></i>
          <span class="alert-text">{{ item.content }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
let seed = 0;

function getUuid() {
  return "alert_" + seed++;
}

export default {
  name: "Alert",
  data() {
    return {
      notices: []
    };
  },
  methods: {
    add(notice) {
      const name = getUuid();

      let _notice = Object.assign(
        {
          name
        },
        notice
      );

      this.notices.push(_notice);

      // 定时移除，单位：秒
      const duration = notice.duration;
      setTimeout(() => {
        this.remove(name);
      }, duration * 1000);
    },
    remove(name) {
      let index = this.notices.findIndex(item => item.name === name);
      this.notices.splice(index, 1);
    }
  }
};
</script>
<style scoped>
.alert {
  position: fixed;
  width: 100%;
  top: 16px;
  left: 0;
  z-index: 1001;
  text-align: center;
  pointer-events: none;
}
.alert-content {
  position: relative;
  display: inline-block;
  padding: 8px 16px;
  background: #fff;
  border-radius: 3px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.2);
  margin-bottom: 8px;
}
.conten {
  display: flex;
  justify-content: center;
  align-items: center;
}

.alert-icon {
  /* position: absolute;
  left: 0;
  top: 0; */
  display: inline-block;
  color: #fff;
  width: 1em;
  height: 1em;
  line-height: 1em;
  margin-right: 8px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: 0 50%;
}

.alert-icon-success {
  background-color: #13ce66;
  background-image: url();
}

.alert-icon-error {
  background-color: #ff4949;
  background-image: url();
}

.alert-icon-info {
  background-color: #20a0ff;
  background-image: url();
}

.alert-icon-warning {
  background-color: #f7ba2a;
  background-image: url();
}
</style>